#!/usr/bin/python

import urllib
import datetime
import time

class BeachData:
	'An object that stores a forecast of a single beach'
	def __init__(self):
		self.beachNumber = ""
		self.beachName = ""
		self.dataDays = []
		self.windDirections = []
		self.windSpeeds = []
		self.starRatings = []
		self.waveSizes = []
		self.swellSizes = []
		self.swellDegrees = []
		self.swellDirections = []
		self.asOf = ""
	
	###########################
	# Remove own bad surf days
	def filterBadDays(self):
		removalCount = 0	# This is used to allow for the fact we're removing elements in lists while looping in one
		for (dataPos, starRating) in enumerate(self.starRatings[:]):
			if (starRating.count('*') < starMinLimit):
				for dataStruct in [self.dataDays, self.windDirections, self.windSpeeds,
								   self.starRatings, self.waveSizes, self.swellSizes,
								   self.swellDegrees, self.swellDirections]:
					dataStruct.pop(dataPos - removalCount)
				removalCount += 1
		return 0
	
	#############################
	# Load beach info from file
	def loadFromFile(self, beachNumber):
		try:
			fileHandle = open('beachData'+beachNumber+'.pkl',mode='r')
		except IOError:
			print "Error opening file beachData%s in loadFromFile()" % beachNumber
		else:
			self.beachNumber = pickle.load(fileHandle)
			self.beachName = pickle.load(fileHandle)
			self.dataDays = pickle.load(fileHandle)
			self.windDirections = pickle.load(fileHandle)
			self.windSpeeds = pickle.load(fileHandle)
			self.starRatings = pickle.load(fileHandle)
			self.waveSizes = pickle.load(fileHandle)
			self.swellSizes = pickle.load(fileHandle)
			self.swellDegrees = pickle.load(fileHandle)
			self.swellDirections = pickle.load(fileHandle)
			self.asOf = pickle.load(fileHandle)
			fileHandle.close()
		return 0
	
	###########################
	# Store info by pickling self
	def storeToFile(self):
		try:
			fileHandle = open("beachData"+self.beachNumber+".pkl",'wb')
		except IOError:
			print "Error opening beachData%s in storeToFile()" % self.beachNumber
		else:
			pickle.dump(self.beachNumber,fileHandle)
			pickle.dump(self.beachName,fileHandle)
			pickle.dump(self.dataDays,fileHandle)
			pickle.dump(self.windDirections,fileHandle)
			pickle.dump(self.windSpeeds,fileHandle)
			pickle.dump(self.starRatings,fileHandle)
			pickle.dump(self.waveSizes,fileHandle)
			pickle.dump(self.swellSizes,fileHandle)
			pickle.dump(self.swellDegrees,fileHandle)
			pickle.dump(self.swellDirections,fileHandle)
			pickle.dump(self.asOf, fileHandle)
			fileHandle.close()
		return 0
	
	###############################
	# Convert a scraped forecast list to an initalised object
	def initFromList(self, beachForecast):
		for dataPos, dataElement in enumerate(beachForecast):	
			if (dataPos == 0):
				self.beachNumber = dataElement
			elif (dataPos == 1):				
				self.beachName = dataElement
			else:								
				self.dataDays.append(dataElement.split(" ")[1])				
				self.starRatings.append(dataElement.split(" ")[3])
				self.waveSizes.append(dataElement.split(" ")[4])
				self.swellSizes.append(dataElement.split(" ")[6])
				self.swellDegrees.append(dataElement.split(" ")[7])
				self.swellDirections.append(dataElement.split(" ")[8])
				self.windSpeeds.append(dataElement.split(" ")[9])
				self.windDirections.append(dataElement.split(" ")[10])
				self.asOf = datetime.date.today()
		return self
	
	##################################################
	# Web scrape page and generate beach forecast info - return self
	def scrapeBeachInfo(self, beachNumber):
		singleBeachForecast = []  # wipe old temp list	
		pageHtml = urllib.urlopen("http://magicseaweed.com/wap/index.php?page=summary&unit=uk&spotId="+beachNumber).read()
		for fileLine in pageHtml.split("\n"):
			if (fileLine.find("<title>") != -1):
				singleBeachForecast.append(beachNumber)
				singleBeachForecast.append(fileLine.split(">")[1].split("-")[0].rstrip()) # Get name of beach
			if (fileLine.find("hour") != -1):
				alteredLine = fileLine.replace("</td><td>", " ")
				alteredLine = alteredLine.replace("&deg;","@")
				alteredLine = alteredLine.replace("\">"," ")
				alteredLine = alteredLine.replace("</a>"," ")
				singleBeachForecast.append(alteredLine.split("&amp")[3])	# Append beach details
		self.initFromList(singleBeachForecast)
		return self
	
	##############################
	# Class -> String function
	def __str__(self):
		return "object: %s\n dataDays=%s\n windDirections=%s\n windSpeeds=%s\n starRatings=%s\n waveSizes=%s\n swellSizes=%s\
				\n swellDegrees=%s\n swellDirections=%s\n asOf=%s\n" % (self.beachName, self.dataDays, self.windDirections, self.windSpeeds,
				self.starRatings, self.waveSizes, self.swellSizes, self.swellDegrees, self.swellDirections, self.asOf)
